from typing import Annotated, List, Optional

from fastapi import APIRouter, Body, Depends, Path, Query

from app.api.deps import CurrentUserDep, require_permission
from app.core import settings
from app.exceptions.base import AppException
from app.models.system import SysUser
from app.schemas.base import Pagination, Response
from app.schemas.notice import (
    NoticeDetailVO,
    NoticeForm,
    NoticePageVO,
    UserNoticePageVO,
)

router = APIRouter(prefix=f"{settings.API_V1_STR}/notices", tags=["09.通知公告"])


@router.get(
    "/page",
    response_model=Response[Pagination[NoticePageVO]],
    summary="通知公告分页列表",
    description="分页查询通知公告列表，需 sys:notice:query 权限",
)
async def get_notice_page(
    current_user: Annotated[SysUser, Depends(require_permission("sys:notice:query"))],
    page_num: int = Query(default=1, min=1, alias="pageNum", description="页码"),
    page_size: int = Query(default=10, min=10, max=1000, alias="pageSize", description="每页记录数"),
    title: Optional[str] = Query(default=None, alias="title", description="通知标题"),
    publish_status: Optional[int] = Query(
        default=None, alias="publishStatus", description="发布状态(0-未发布 1已发布 -1已撤回)"
    ),
    publish_time: Optional[List[str]] = Query(default=None, alias="publishTime", description="发布时间(起止)"),
    user_id: Optional[int] = Query(default=None, alias="userId", description="查询人ID"),
    is_read: Optional[int] = Query(default=None, alias="isRead", description="是否已读（0-未读 1-已读）"),
) -> Response[Pagination[NoticePageVO]]:
    """
    通知公告分页列表
    """
    try:
        return Response.success(data=Pagination[NoticePageVO](list=[], total=0, page_size=page_size, page_num=page_num))
    except Exception as e:
        raise AppException(message="获取通知公告分页列表失败") from e


@router.post(
    "", response_model=Response[None], summary="新增通知公告", description="创建新的通知公告，需 sys:notice:add 权限"
)
async def save_notice(
    current_user: Annotated[SysUser, Depends(require_permission("sys:notice:add"))],
    form_data: Annotated[NoticeForm, Body(..., description="通知公告表单数据")],
) -> Response[None]:
    """
    新增通知公告
    """
    try:
        return Response.success(data=None)
    except Exception as e:
        raise AppException(message="新增通知公告失败") from e


@router.get(
    "/{id}/form",
    response_model=Response[NoticeForm],
    summary="获取通知公告表单数据",
    description="根据通知公告ID获取编辑表单数据，需 sys:notice:edit 权限",
)
async def get_notice_form(
    id: Annotated[int, Path(..., description="通知公告ID")],
    current_user: Annotated[SysUser, Depends(require_permission("sys:notice:edit"))],
) -> Response[NoticeForm]:
    """
    获取通知公告表单数据
    """
    try:
        return Response.success(data=NoticeForm())
    except Exception as e:
        raise AppException(message="获取通知公告表单数据失败") from e


@router.get(
    "/{id}/detail",
    response_model=Response[NoticeDetailVO],
    summary="阅读获取通知公告详情",
    description="获取指定通知公告的详细内容（标记为已读）",
)
async def get_notice_detail(
    id: Annotated[int, Path(..., description="通知公告ID")],
    current_user: CurrentUserDep,
) -> Response[NoticeDetailVO]:
    """
    阅读获取通知公告详情
    """
    try:
        return Response.success(data=NoticeDetailVO())
    except Exception as e:
        raise AppException(message="获取通知公告详情失败") from e


@router.put(
    "/{id}",
    response_model=Response[None],
    summary="修改通知公告",
    description="更新通知公告内容，需 sys:notice:edit 权限",
)
async def update_notice(
    id: Annotated[int, Path(..., description="通知公告ID")],
    form_data: Annotated[NoticeForm, Body(..., description="通知公告表单数据")],
    current_user: Annotated[SysUser, Depends(require_permission("sys:notice:edit"))],
) -> Response[None]:
    """
    修改通知公告
    """
    try:
        return Response.success(data=None)
    except Exception as e:
        raise AppException(message="修改通知公告失败") from e


@router.put(
    "/{id}/publish",
    response_model=Response[None],
    summary="发布通知公告",
    description="将草稿状态的通知公告发布，需 sys:notice:publish 权限",
)
async def publish_notice(
    id: Annotated[int, Path(..., description="通知公告ID")],
    current_user: Annotated[SysUser, Depends(require_permission("sys:notice:publish"))],
) -> Response[None]:
    """
    发布通知公告
    """
    try:
        return Response.success(data=None)
    except Exception as e:
        raise AppException(message="发布通知公告失败") from e


@router.put(
    "/{id}/revoke",
    response_model=Response[None],
    summary="撤回通知公告",
    description="撤回已发布的通知公告，需 sys:notice:revoke 权限",
)
async def revoke_notice(
    id: Annotated[int, Path(..., description="通知公告ID")],
    current_user: Annotated[SysUser, Depends(require_permission("sys:notice:revoke"))],
) -> Response[None]:
    """
    撤回通知公告
    """
    try:
        return Response.success(data=None)
    except Exception as e:
        raise AppException(message="撤回通知公告失败") from e


@router.delete(
    "/{ids}",
    response_model=Response[None],
    summary="删除通知公告",
    description="批量删除通知公告，多个ID用英文逗号分隔，需 sys:notice:delete 权限",
)
async def delete_notices(
    ids: Annotated[str, Path(..., description="通知公告ID，多个以英文逗号(,)分割")],
    current_user: Annotated[SysUser, Depends(require_permission("sys:notice:delete"))],
) -> Response[None]:
    """
    删除通知公告
    """
    try:
        return Response.success(data=None)
    except Exception as e:
        raise AppException(message="删除通知公告失败") from e


@router.put(
    "/read-all", response_model=Response[None], summary="全部已读", description="将当前用户所有未读通知标记为已读"
)
async def read_all(
    current_user: CurrentUserDep,
) -> Response[None]:
    """
    全部已读
    """
    try:
        return Response.success(data=None)
    except Exception as e:
        raise AppException(message="全部已读失败") from e


@router.get(
    "/my-page",
    response_model=Response[Pagination[UserNoticePageVO]],
    summary="获取我的通知公告分页列表",
    description="分页查询当前用户收到的通知公告",
)
async def get_my_notice_page(
    current_user: CurrentUserDep,
    page_num: int = Query(default=1, min=1, alias="pageNum", description="页码"),
    page_size: int = Query(default=10, min=10, max=1000, alias="pageSize", description="每页记录数"),
    title: Optional[str] = Query(default=None, alias="title", description="通知标题"),
    publish_status: Optional[int] = Query(
        default=None, alias="publishStatus", description="发布状态(0-未发布 1已发布 -1已撤回)"
    ),
    publish_time: Optional[List[str]] = Query(default=None, alias="publishTime", description="发布时间(起止)"),
    user_id: Optional[int] = Query(default=None, alias="userId", description="查询人ID"),
    is_read: Optional[int] = Query(default=None, alias="isRead", description="是否已读（0-未读 1-已读）"),
) -> Response[Pagination[UserNoticePageVO]]:
    """
    获取我的通知公告分页列表
    """
    try:
        return Response.success(
            data=Pagination[UserNoticePageVO](list=[], total=0, page_size=page_size, page_num=page_num)
        )
    except Exception as e:
        raise AppException(message="获取我的通知公告分页列表失败") from e
